import {Card, DatePicker, Table} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {TableListItem} from './data.d';
import {queryOverview} from './service';
import {columnsSorter, columnToColumnsState, empty, getNowFormatDate, NumberMul} from "@/utils/function";
import {queryUse} from "@/utils/service";

const Overview: React.FC = () => {
  let columns: any[] = [
    {
      title: "用户",
      dataIndex: 'nickname',
      key: 'nickname',
      width: 120,
      tip: '用户是唯一的 key',
    },
    {
      title: "交易对",
      dataIndex: 'symbol',
      key: 'symbol',
      width: 100,
    },

    {
      title: "成本",
      width: 120,
      dataIndex: 'principal',
      key: 'principal',
    },
    {
      title: "盈亏",
      width: 120,
      dataIndex: 'profit',
      key: 'profit',
    },
    {
      title: "用户类型",
      dataIndex: 'userType',
      key: 'userType',
      width: 120,
    },
    {
      title: "用户类型描述",
      dataIndex: 'userTypeDesc',
      key: 'userTypeDesc',
      width: 200,
    },
  ];
  columnsSorter("Overview总览", columns);
  const [col, setCol] = useState<any>(columnToColumnsState(columns));

  // const [dataTable, setDataTable] = useState<any>(null);
  const [dateS, setDateS] = useState<any>(null);
  const [dataSourceTotal, setDataSourceTotal] = useState<any>([]);
  const actionRef = useRef<ActionType>();

  useEffect(() => {
    console.log(dateS);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }, [dateS])


  let columnsTotal = [
    {
      title: "类型",
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: "成本",
      dataIndex: 'cost',
      key: 'cost',
    },
    {
      title: "盈亏",
      dataIndex: 'profit',
      key: 'profit',
    },
  ]

  return (
    <PageContainer>
      <Card>
        <Table
          columns={columnsTotal}
          dataSource={dataSourceTotal}
          pagination={false}
          bordered
          size={"small"}
        />
        <ProTable<TableListItem>
          headerTitle={""}
          rowKey="key"
          bordered
          actionRef={actionRef}
          columnsStateMap={col}
          onColumnsStateChange={(e) => {
            if (!empty(e)) {
              localStorage.setItem("Overview总览", JSON.stringify(e));
              setCol(e);
            }
          }}
          toolBarRender={() => [
            // <div style={{margin: 20}}>成本合计:&nbsp;&nbsp;{costTotal}</div>,
            // <div style={{margin: 20}}>盈利合计:&nbsp;&nbsp;{profitTotal}</div>,
            <div>
              选择起始日期:&nbsp;&nbsp;
              <DatePicker
                // showTime
                format="YYYY-MM-DD"
                placeholder="请选择"
                style={{width: 200, margin: 20, marginLeft: 10}}
                onChange={(e) => {
                  setDateS(getNowFormatDate((e ? e : null)));
                }}
              />
            </div>,
          ]}
          params={{date: dateS}}
          pagination={false}
          scroll={{x: 1200, y: 666}}
          search={false}
          request={async (params = {}, sort: any, filter: any) => {
            // console.log(params.toString());
            const msg = await queryOverview(params.date);
            let data = queryUse(msg);
            let dataSourceTotal = [];
            let costTotal = {"合计": 0};
            let profitTotal = {"合计": 0};
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              costTotal["合计"] += NumberMul(item.principal || 0, 1, 2) || 0;
              profitTotal["合计"] += NumberMul(item.profit || 0, 1, 2) || 0;
              if (!costTotal[item.userTypeDesc]) {
                costTotal[item.userTypeDesc] = item.principal || 0;
              } else {
                costTotal[item.userTypeDesc] += NumberMul(item.principal || 0, 1, 2) || 0;
              }
              if (!profitTotal[item.userTypeDesc]) {
                profitTotal[item.userTypeDesc] = item.profit || 0;
              } else {
                profitTotal[item.userTypeDesc] += NumberMul(item.profit || 0, 1, 2) || 0;
              }
            }
            for (let i in costTotal) {
              for (let j in profitTotal) {
                if (i === j) {
                  dataSourceTotal.push({type: i, cost:  NumberMul(costTotal[i],1,2), profit: NumberMul(profitTotal[i],1,2) ,})
                }
              }
            }

            setDataSourceTotal(dataSourceTotal)
            if (data) {
              return {
                data: data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                // total: number,
              };
            } else {
              return {
                data: [],
                success: false,
              };
            }
          }}
          columns={columns}
        />
      </Card>
    </PageContainer>
  );
};

export default Overview;
